﻿using UnityEngine;
using UnityEditor;
using System.Collections;
using System;

public class BTNodeEditorWindow : EditorWindow
{
    #region variables
    public static BTNodeEditorWindow curWindow;

    public BTNodePropertyView propertyView;
    public BTNodeWorkView workView;

    public float viewPrecentage = 0.75f;

    public BTNodeGraph curGraph = null;
    ///数据
    public BTreeEditorData treeEditorData;
    #endregion

    #region Main Methods
    public static void InitEditorWindow()
    {
        BTreeEditorData.initData();
        curWindow = EditorWindow.GetWindow<BTNodeEditorWindow>();
        curWindow.titleContent = new GUIContent("Node Editor");
        Debug.Log("InitEditorWindow!");
        //  CreateViews();
    }

   

    //编辑器回调
    void OnEnable()
    {
        curWindow = EditorWindow.GetWindow<BTNodeEditorWindow>();
        if (propertyView == null || workView == null)
        {
            CreateViews();
            return;
        }
        Debug.Log("Enable Window!"); 
    }

    void OnDestroy()
    {
        Debug.Log("Destory Window!");
    }

    void Update()
    {
       // Debug.Log("Update");

    }

    void OnGUI()
    {
        if (propertyView == null || workView == null)
        {
            CreateViews();
            return;
        }
        // EditorGUILayout.LabelField("节点编辑器");
        //   Debug.Log("x:"+position.x+"y:"+position.y);

        //Get and process the current Event
        Event e = Event.current;
        ProcessEvents(e);

        //Update views
        workView.UpdateView(position, new Rect(0f, 0f, this.viewPrecentage, 1f),e, curGraph);
        propertyView.UpdateView(new Rect(position.width, position.y, position.width, position.height),
                                new Rect(this.viewPrecentage, 0f, 1 - this.viewPrecentage, 1f),e, curGraph);

        Repaint();
       
    }

   
    #endregion

    #region Utility Methods
    static void CreateViews()
    {
        if (curWindow == null)
            curWindow = EditorWindow.GetWindow <BTNodeEditorWindow>() ;

        curWindow.propertyView = new BTNodePropertyView();
        curWindow.workView = new BTNodeWorkView();
    }

    private void ProcessEvents(Event e)
    {
        if (e.type == EventType.KeyDown && e.keyCode == KeyCode.LeftArrow)
        {
            viewPrecentage -= 0.01f;
        }

        if (e.type == EventType.KeyDown && e.keyCode == KeyCode.RightArrow)
        {
            viewPrecentage += 0.01f;
        }
    }

    static public Vector2 getWorkViewOffset()
    {
        if(curWindow!=null && curWindow.workView!= null)
        {
            return curWindow.workView.offsetScroll;
        }
        return Vector2.zero;
    }
    #endregion

}
